package cn.sylinx.redis.springboot;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.FactoryBean;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisSentinelPool;
import redis.clients.util.Pool;

public class SpringJedisPoolFactoryBean implements FactoryBean<Pool<Jedis>>  {

	private Pool<Jedis> pool = null;

	private GenericObjectPoolConfig poolConfig;

	private String server; // IP:Port or mymaster,192.168.2.212:26379

	public void setPoolConfig(GenericObjectPoolConfig poolConfig) {
		this.poolConfig = poolConfig;
	}

	public void setServer(String server) {
		this.server = server;
	}

	@Override
	public Pool<Jedis> getObject() throws Exception {
		if (pool == null) {
			synchronized (this) {
				if (pool == null) {
					pool = createPool();
				}
			}
		}
		return pool;
	}

	private Pool<Jedis> createPool() {
		GenericObjectPoolConfig config = new GenericObjectPoolConfig();
		if (this.poolConfig != null) {
			config = this.poolConfig;
		}

		if (this.server != null) {
			String[] splits = this.server.split(",");

			if (splits.length == 1) {
				String[] subs = splits[0].split(":");
				if (subs.length == 2) {
					return new JedisPool(config, subs[0], Integer.parseInt(subs[1]));
				}
			} else if (splits.length > 1) {
				String name = splits[0];
				Set<String> sentinels = new HashSet<String>();
				for (int i = 1; i < splits.length; i++) {
					sentinels.add(splits[i]);
				}
				return new JedisSentinelPool(name, sentinels, config);
			}
		}

		throw new RuntimeException(
				"server配置不正确。\n配置形式1: redis_ip:redis_port、\n配置方式2: mastername,sentinel1_ip:sentinel1_port,sentinel2_ip:sentinel2_port,...");
	}

	@Override
	public Class<?> getObjectType() {
		return Pool.class;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}

}
